package cn.csq.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author chengshanqing
 * @date Created in 2022/03/29 17:31
 */
public class StatisProxyTest {
    public static void main(String[] args) {

        String name = "test";
        //使用代理对象完成
        UserService adminUserService = new AdminUserService();
        UserServiceProxy userServiceProxy = new UserServiceProxy(adminUserService);
        String adminProxy = userServiceProxy.getUserProxy(name);
        System.out.println("adminProxy = " + adminProxy);

        MobileServiceImpl mobileServiceImpl = new MobileServiceImpl();
        userServiceProxy = new UserServiceProxy(mobileServiceImpl);
        String mobileProxy = userServiceProxy.getUserProxy(name);
        System.out.println("mobileProxy = " + mobileProxy);

        //动态代理
        //Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), , new InvocationHandler() {
        //    @Override
        //    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //        return null;
        //    }
        //})
        //生成动态代理类
        //Class<?> proxyClass = Proxy.getProxyClass(UserService.class.getClassLoader(), new Class<?>[]{UserService.class});

        //jdk动态代理
        UserService newProxyInstance = (UserService) Proxy.newProxyInstance(UserService.class.getClassLoader(), new Class[]{UserService.class}
                , new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("代理执行 开始");
                        Object invoke = method.invoke(proxy, args);
                        System.out.println("代理执行 完毕");
                        return invoke;
                    }
                });

        String test = newProxyInstance.getUser("test");
        System.out.println("test = " + test);
    }
}
